package com.mysqldemo.controller;

import com.mysqldemo.exception.BusinessException;

import com.mysqldemo.enums.ResponseCodeEnum;

import com.mysqldemo.entity.vo.ResponseVO;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import javax.servlet.http.HttpServletRequest;
import java.net.BindException;

/**
 * @Author xiaoyi
 * @Version 1.0
 * @ClassName AGlobalExceptionHandlerController
 * @Time 22:21
 */
@RestControllerAdvice
public class AGlobalExceptionHandlerController extends ABaseController{
    private static final Logger logger  = LoggerFactory.getLogger(AGlobalExceptionHandlerController.class);
    @ExceptionHandler(value = Exception.class)
    Object handleException(Exception e, HttpServletRequest request){
        logger.error("请求错误url {},msg {}",request.getRequestURL(),e.getMessage());
        ResponseVO ajaxResponse = new ResponseVO();
        //404
        if(e instanceof org.springframework.web.servlet.NoHandlerFoundException){
            ajaxResponse.setCode(ResponseCodeEnum.NOT_FOUND.getCode());
            ajaxResponse.setInfo(ResponseCodeEnum.NOT_FOUND.getMessage());
            ajaxResponse.setStatus(ERROR);
        }else if(e instanceof BusinessException){
            //业务异常
            BusinessException businessException = (BusinessException) e;
            ajaxResponse.setCode(businessException.getCode());
            ajaxResponse.setInfo(businessException.getMessage());
            ajaxResponse.setStatus(ERROR);
        }else if(e instanceof BindException){
            //参数异常
            BindException bindException = (BindException) e;
            ajaxResponse.setCode(ResponseCodeEnum.PARAM_ERROR.getCode());
            ajaxResponse.setInfo(bindException.getMessage());
            ajaxResponse.setStatus(ERROR);

        } else if (e instanceof DuplicateKeyException) {
            //主键冲突
            ajaxResponse.setCode(ResponseCodeEnum.PRIMARY_KEY_CONFLICT.getCode());
            ajaxResponse.setInfo(ResponseCodeEnum.PRIMARY_KEY_CONFLICT.getMessage());
            ajaxResponse.setStatus(ERROR);
        }else{
            //其他异常
            ajaxResponse.setCode(ResponseCodeEnum.ERROR.getCode());
            ajaxResponse.setInfo(ResponseCodeEnum.ERROR.getMessage());
            ajaxResponse.setStatus(ERROR);
        }
        return ajaxResponse;
    }
}
